//
// Created by bd on 2019/11/10.
//

#include <iostream>
#include <csignal>
#include <event2/event.h>

using namespace std;

static void c_cb(evutil_socket_t fb, short what, void *arg)
{
    cout << "c cb" << endl;
}

static void kill_cb(evutil_socket_t fb, short what, void *arg)
{
    cout << "kill cb" << endl;

    auto ev = reinterpret_cast<event *>(arg);
    if (!evsignal_pending(ev, NULL)) {
        event_del(ev);
        event_add(ev, NULL);
    }
}

int main()
{
    auto *base = event_base_new();
    if (!base) {
        cerr << "event base new failed." << endl;
        return 1;
    }

    auto csig = evsignal_new(base, SIGINT, c_cb, base);
    if (!csig) {
        cerr << "SIGINT evsignal new failed" << endl;
        return 1;
    }

    event_add(csig, NULL);
    auto ksig = event_new(base, SIGTERM, EV_SIGNAL, kill_cb, event_self_cbarg());
    if (!ksig) {
        cerr << "SIGTERM event new failed" << endl;
        return 1;
    }
    event_add(ksig, NULL);

    event_base_dispatch(base);

    event_free(ksig);
    event_base_free(base);

    return 0;
}
